/*******************************************************************************
* Copyright (c) 2010, 2018 西安秦晔信息科技有限公司
* Licensed under the Apache License, Version 2.0 (the "License");
*    you may not use this file except in compliance with the License.
*    You may obtain a copy of the License at
*
*       http://www.apache.org/licenses/LICENSE-2.0
*
*    Unless required by applicable law or agreed to in writing, software
*    distributed under the License is distributed on an "AS IS" BASIS,
*    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*    See the License for the specific language governing permissions and
*    limitations under the License.
*******************************************************************************/
package com.qinyeit.webapp.controller.management.dishes;

import com.alibaba.fastjson.JSONObject;
import com.qinyeit.serviceapp.entity.DishesMakeCategory;
import com.qinyeit.serviceapp.entity.DishesMakeRelation;
import com.qinyeit.serviceapp.entity.enums.ChooseType;
import com.qinyeit.serviceapp.entity.enums.PriceupType;
import com.qinyeit.serviceapp.entity.enums.State;
import com.qinyeit.serviceapp.service.dishes.DishesMakeCategoryService;
import com.qinyeit.serviceapp.service.dishes.DishesMakeRelationService;
import com.qinyeit.serviceapp.utils.LocalUtils;
import com.qinyeit.webapp.controller.management.BaseManagementController;
import com.qinyeit.webapp.utils.CurrentAccountUtils;
import com.qinyeit.webapp.utils.SearchableUtils;
import com.qinyetech.springstage.core.date.DateUtils;
import com.qinyetech.springstage.core.entity.search.Searchable;
import com.qinyetech.springstage.core.lang.QyMap;
import com.qinyetech.springstage.core.utils.JSONUtils;
import com.qinyetech.springstage.core.web.annotation.PageableDefaults;
import com.qinyetech.springstage.core.web.annotation.PermissionInfo;
import com.qinyetech.springstage.core.web.dto.ResponseResult;

import com.qinyeit.serviceapp.entity.DishesMake;
import com.qinyeit.serviceapp.service.dishes.DishesMakeService;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Calendar;
import java.util.List;

/**
 * ClassName: DishesMakesController <br/>
 * Function: dishesMake [菜品做法] <br/>
 * date: 2018-11-23 13:41:16 <br/>
 *
 * @author liuwenjin
 * @version  1.0
 * @since JDK 1.8
 */
@RestController
@RequestMapping("/management/dishes/dishesMakes")
@PermissionInfo(parentName ="基础信息管理" ,parentOrder = 10,order = 10,code = "management_dishesMake:read",name ="菜品做法",deleteAble = false)
public class DishesMakesController extends BaseManagementController{

	@Autowired
	private DishesMakeService dishesMakeService;
	@Autowired
	private DishesMakeCategoryService dishesMakeCategoryService;
	@Autowired
	private DishesMakeRelationService dishesMakeRelationService;
    //TODO include的字段,支持jsonPath
	private final String [] keys = {"id","storeId","name","priceupType","priceupValue","state","createAt","type.name:typeName","type.id:typeId"};

    @RequiresPermissions("management_dishes:show")
    @PermissionInfo(code = "management_dishesMake:show",name ="查看",deleteAble = false)
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST})
    @PageableDefaults(sort = "id=desc")//默认按照id降序
    public ResponseResult<JSONObject> index(Searchable searchable,Long storeId){
        if(storeId==null){
            return fail("查询失败");
        }
        searchable = SearchableUtils.newSearchableWithMerchantFilter(searchable);
        searchable.addSearchParam("storeId_eq",storeId);
        Page<DishesMake> dishesMakePage = dishesMakeService.findAll(searchable);
        QyMap map = QyMap.map("dishesMakePage",JSONUtils.include(dishesMakePage, keys));
        initFormDate(map,storeId,"index");
        return ok("查询成功",map );
    }

    @GetMapping("/create")
    public ResponseResult<QyMap> _new(Long storeId){
        if (storeId==null){
            return fail("查询失败");
        }
        QyMap map=QyMap.NEW();
        map.setv("dishesMake",JSONUtils.include(new DishesMake(), keys));
        initFormDate(map,storeId,""); //TODO 如果没有需要初始化的数据，测则删除该行
        return ok("初始化成功", map);
    }

    @RequiresPermissions("management_dishes:edit")
    @PermissionInfo(code = "management_dishesMake:create",name ="新增",deleteAble = false)
    @PostMapping("/create")
    public ResponseResult<String> create(@ModelAttribute @Valid DishesMake dishesMake, BindingResult bindingResult){
//        if(dishesMakeService.exists(buildExists(null, "no", dishesMake.getNo()))){
//             bindingResult.rejectValue("no","no.error","编号已经存在");
//        }
        if (bindingResult.hasErrors()) {
            return super.validateFail(bindingResult);
        }
        dishesMake.setUuid(LocalUtils.getUUID());
        dishesMake.setUpdateTimestamp(DateUtils.current());
        dishesMake.setMerchantGroupId(CurrentAccountUtils.getAuthenticatedMerchantGroupID());
        dishesMakeService.save(dishesMake);
        return ok("保存成功");
    }

    @GetMapping("/{id}")
    public ResponseResult<JSONObject> show(@ModelAttribute DishesMake dishesMake){
        return ok("查询成功", JSONUtils.include(dishesMake, keys));
    }

    @GetMapping("/{id}/update")
    public ResponseResult<QyMap> edit(@ModelAttribute DishesMake dishesMake,Long storeId){
        if (storeId==null){
            return fail("查询失败");
        }
        QyMap map=QyMap.NEW();
        map.setv("dishesMake",JSONUtils.include(dishesMake, keys));
        initFormDate(map,storeId,""); //TODO 如果没有需要初始化的数据，测则删除该行
        return ok("查询成功",map);
    }

    @RequiresPermissions("management_dishes:edit")
    @PermissionInfo(code = "management_dishesMake:update",name ="修改",deleteAble = false)
    @PutMapping("/{id}/update")
    public ResponseResult<String> update(@ModelAttribute @Valid DishesMake dishesMake,BindingResult bindingResult){
//        if(dishesMakeService.exists(buildExists(null, "no", dishesMake.getNo()))){
//             bindingResult.rejectValue("no","no.error","编号已经存在");
//        }
        if (bindingResult.hasErrors()) {
            return super.validateFail(bindingResult);
        }
        dishesMake.setUpdateTimestamp(DateUtils.current());
        dishesMake.setMerchantGroupId(CurrentAccountUtils.getAuthenticatedMerchantGroupID());
        dishesMakeService.update(dishesMake);
        return ok("更新成功", null);
    }

    @RequiresPermissions("management_dishes:edit")
    @PermissionInfo(code = "management_dishesMake:destory",name ="删除",deleteAble = false)
    @DeleteMapping("/{id}")
    public ResponseResult<String> destory(@PathVariable Long id){
        Searchable searchable = SearchableUtils.newSearchableWithMerchantFilter();
        searchable.addSearchParam("makeId_eq",id);
        Long count = dishesMakeRelationService.count(searchable);
        if (count.intValue()>0){
            return fail("做法正在使用不能删除");
        }
        DishesMake make = dishesMakeService.findById(id);
        make.setUpdateTimestamp(DateUtils.current());
        dishesMakeService.update(make);
        dishesMakeService.logicDelete(id);
        return ok("删除成功", null);
    }

    @ModelAttribute
    public void preparedData(@PathVariable(value="id",required = false) String id,Model model){
        if(StringUtils.isNotBlank(id)){ //如果路径中有id参数则查询实体对象
            DishesMake dishesMake = dishesMakeService.findById(Long.valueOf(id));
            model.addAttribute(dishesMake);
        }
    }

    /**
     * 初始化表单数据
     * @param qyMap
     */
    private void initFormDate(QyMap qyMap,Long storeId,String type){
        //加价方式
       qyMap.setv("priceupTypes", PriceupType.values());
       //做法分类
        Searchable searchable = SearchableUtils.newSearchableWithMerchantFilter();
        searchable.addSearchParam("storeId_eq",storeId);
        List<DishesMakeCategory> list = dishesMakeCategoryService.findWithSort(searchable);

        if (CollectionUtils.isNotEmpty(list)){
            for (DishesMakeCategory category : list) {
                category.setCount(dishesMakeService.getCountByType(category.getId(),storeId));
            }
        }
        if(StringUtils.isNotBlank(type) && type.equals("index")){
            DishesMakeCategory category = DishesMakeCategory.builder().
                    name("全部做法").
                    state(State.NORMAL).
                    count(dishesMakeService.getCountByType(null,storeId)).
                    storeId(storeId).build();
            list.add(0,category);
        }

        qyMap.setv("makeCategorys",JSONUtils.include(list,new Class[]{State.class, ChooseType.class},"id","name","chooseType","state","count"));
    }

}